/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.bluetoothlegatt;

import android.app.Activity;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

/**
 * For a given BLE device, this Activity provides the user interface to connect, display data,
 * and display GATT services and characteristics supported by the device.  The Activity
 * communicates with {@code BluetoothLeService}, which in turn interacts with the
 * Bluetooth LE API.
 */
public class DeviceControlActivity extends Activity {
    private final static String TAG = DeviceControlActivity.class.getSimpleName();

    public static final String EXTRAS_DEVICE_NAME = "DEVICE_NAME";
    public static final String EXTRAS_DEVICE_ADDRESS = "DEVICE_ADDRESS";

    private TextView mConnectionState;
    private TextView mDataField;
    private String mDeviceName;
    private String mDeviceAddress;
    private BluetoothLeService mBluetoothLeService;
    private boolean mConnected = false;
    private BluetoothGattCharacteristic mNotifyCharacteristic;
    private BluetoothGattCharacteristic mWriteCharacteristic;

    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
            if (!mBluetoothLeService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            // Automatically connects to the device upon successful start-up initialization.
            mBluetoothLeService.connect(mDeviceAddress);
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBluetoothLeService = null;
        }
    };

    // Handles various events fired by the Service.
    // ACTION_GATT_CONNECTED: connected to a GATT server.
    // ACTION_GATT_DISCONNECTED: disconnected from a GATT server.
    // ACTION_GATT_SERVICES_DISCOVERED: discovered GATT services.
    // ACTION_DATA_AVAILABLE: received data from the device.  This can be a result of read
    //                        or notification operations.
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            Log.w("qob", "action: " + action);
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                mConnected = true;
                updateConnectionState(R.string.connected);
                invalidateOptionsMenu();
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                mConnected = false;
                updateConnectionState(R.string.disconnected);
                invalidateOptionsMenu();
                clearUI();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                // Show all the supported services and characteristics on the user interface.
                displayGattServices(mBluetoothLeService.getSupportedGattServices());
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] tRecvData = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);

                if (tRecvData ==null || tRecvData.length < 0){
                    Log.w("qob", "tRecvData length < 0");
                    return;
                }

                int tDataType = (tRecvData[0] & 0xff);

                if (tDataType == 0x90){ //从机发送秘钥数据

                    int[] b = new int[16];
                    for (int i = 0; i < 16; ++i){
                        b[i] = (tRecvData[i + 1] & 0xff);
                    }
                    int[] keyStart = {0x73, 0x68, 0x61, 0x6e, 0x72, 0x65, 0x6e, 0x64,
                            0x69, 0x73, 0x63, 0x6f, 0x76, 0x65, 0x72, 0x79};

                    TI_aes_128 tiAes = new TI_aes_128();
                    byte[] encryptedData = tiAes.aes_enc_dec(b, keyStart, (byte)0);

                    Log.w("qob", "encryptedData: " + ByteUtil.byte2hex(encryptedData));

                    byte[] paird91 = new byte[17];
                    paird91[0] = (byte)0x91;
                    System.arraycopy(encryptedData, 0, paird91, 1, 16);

                    sendBleData(paird91);  //主机传输回应密文数据
                }
                else if (tDataType == 0x91){
                    Log.w("qob", "从机秘钥验证ACK数据格式");
                }
                else if (tDataType == 0x11){
                    Log.w("qob", "接收到 体重数据 回复");
                }
                else if (tDataType == 0x13){
                    Log.w("qob", "接收到 时间数据 回复");
                }
                displayData(intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA).toString());
            }
        }
    };

    private void clearUI() {
        mDataField.setText(R.string.no_data);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gatt_services_characteristics);

        final Intent intent = getIntent();
        mDeviceName = intent.getStringExtra(EXTRAS_DEVICE_NAME);
        mDeviceAddress = intent.getStringExtra(EXTRAS_DEVICE_ADDRESS);

        // Sets up UI references.
        ((TextView) findViewById(R.id.device_address)).setText(mDeviceAddress);
        mConnectionState = (TextView) findViewById(R.id.connection_state);
        mDataField = (TextView) findViewById(R.id.data_value);

        getActionBar().setTitle(mDeviceName);
        getActionBar().setDisplayHomeAsUpEnabled(true);
        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        if (mBluetoothLeService != null) {
            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
            Log.d(TAG, "Connect request result=" + result);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mGattUpdateReceiver);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);
        mBluetoothLeService = null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.gatt_services, menu);
        if (mConnected) {
            menu.findItem(R.id.menu_connect).setVisible(false);
            menu.findItem(R.id.menu_disconnect).setVisible(true);
        } else {
            menu.findItem(R.id.menu_connect).setVisible(true);
            menu.findItem(R.id.menu_disconnect).setVisible(false);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.menu_connect:
                mBluetoothLeService.connect(mDeviceAddress);
                return true;
            case R.id.menu_disconnect:
                mBluetoothLeService.disconnect();
                return true;
            case android.R.id.home:
                onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void updateConnectionState(final int resourceId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mConnectionState.setText(resourceId);
            }
        });
    }

    private void displayData(String data) {
        if (data != null) {
            mDataField.setText(data);
        }
    }

    // Demonstrates how to iterate through the supported GATT Services/Characteristics.
    // In this sample, we populate the data structure that is bound to the ExpandableListView
    // on the UI.
    private void displayGattServices(List<BluetoothGattService> gattServices) {
        if (gattServices == null) return;
        String uuid = null;

        // Loops through available GATT Services.
        for (BluetoothGattService gattService : gattServices) {
            uuid = gattService.getUuid().toString();
            Log.w("rd60", "gattService " + uuid);

            if (uuid.equalsIgnoreCase("be940000-7333-be46-b7ae-689e71722bd5")) {

                List<BluetoothGattCharacteristic> gattCharacteristics =
                        gattService.getCharacteristics();


                // Loops through available Characteristics.
                for (BluetoothGattCharacteristic characteristic : gattCharacteristics) {

                    uuid = characteristic.getUuid().toString();
                    final int charaProp = characteristic.getProperties();

                    Log.w("rd60", "charaProp " + charaProp  + " PROPERTY_READ " + uuid);

                    if (uuid.equalsIgnoreCase("be940001-7333-be46-b7ae-689e71722bd5")){

//                        mBluetoothLeService.readCharacteristic(characteristic);

                        mBluetoothLeService.setCharacteristicNotification(
                                characteristic, true);
                        mWriteCharacteristic = characteristic;
                    }
                    else if (uuid.equalsIgnoreCase("be940003-7333-be46-b7ae-689e71722bd5")){

                        mNotifyCharacteristic = characteristic;
//                        mBluetoothLeService.setCharacteristicNotification(
//                                characteristic, true);

                    }

//                    if (charaProp == 16) {
//
//                        mNotifyCharacteristic = characteristic;
//                        mBluetoothLeService.setCharacteristicNotification(
//                                characteristic, true);
//                        mBluetoothLeService.readCharacteristic(mNotifyCharacteristic);
//                    } else {
//                        mWriteCharacteristic = characteristic;
//                    }
                }
            }

        }

    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    public void onClickTestData(View view) {

        if (view.getId() == R.id.btCustomBind) {
            //07000700 0048f3
            byte[] testData = {0x07, 0x00, 0x07, 0x00, 0x00, (byte) 0x48, (byte)0xf3}; //主机请求绑定

            sendBleData(testData);
        }
        else if (view.getId() == R.id.btSettingWeight){
            int tWeight = 800; // 80kg * 10
            //07010900 00000056 05
            byte[] tSendByte = {0x07,0x01,0x09,0x00,0x00,0x00,0x00,0x56,0x05};
//            int offset = 0;
//            tSendByte[offset++] = 0x11;
//            tSendByte[offset++] = 0x01;
//            tSendByte[offset++] = 0x01; //0x01：写
//            tSendByte[offset++] = (byte)(tWeight >> 8);
//            tSendByte[offset++] = (byte)(tWeight & 0xff);

            sendBleData(tSendByte);
        }
        else if (view.getId() == R.id.btSettingTime){
//            int tTimeSecondTo1970 = 1494656743; // 2017/05/13 14:25
//            byte[] tSendByte = new byte[8];
//            int offset = 0;
//            tSendByte[offset++] = 0x13;
//            tSendByte[offset++] = 0x05;
//            tSendByte[offset++] = 0x01; //0x01：写
//            tSendByte[offset++] = (byte)(tTimeSecondTo1970 >> 24);
//            tSendByte[offset++] = (byte)((tTimeSecondTo1970 >> 16) & 0xff);
//            tSendByte[offset++] = (byte)((tTimeSecondTo1970 >> 8) & 0xff);
//            tSendByte[offset++] = (byte)(tTimeSecondTo1970 & 0xff);
//            tSendByte[offset++] = (byte)28; // 默认28（东8区）
//
//            sendBleData(tSendByte);

            mBluetoothLeService.setCharacteristicNotification(
                    mNotifyCharacteristic, true);
 //           mBluetoothLeService.readCharacteristic(mNotifyCharacteristic);
        }
        else if (view.getId() == R.id.btLightSwitch){

//            byte[] tSendByte = new byte[4];
//            int offset = 0;
//            tSendByte[offset++] = 0x13;
//            tSendByte[offset++] = 0x01;
//            tSendByte[offset++] = 0x01; //0x01：写
//            tSendByte[offset++] = 0x01;
//
//            sendBleData(tSendByte);

        }
        else if (view.getId() == R.id.btLightOffSwitch){

            byte[] tSendByte = new byte[4];
            int offset = 0;
            tSendByte[offset++] = 0x13;
            tSendByte[offset++] = 0x01;
            tSendByte[offset++] = 0x01; //0x01：写
            tSendByte[offset++] = 0x0;

            sendBleData(tSendByte);
        }
    }

    public void sendBleData(byte[] bytes) {
        mWriteCharacteristic.setValue(bytes);
        mBluetoothLeService.writeBleData(mWriteCharacteristic);
    }
}
